package example;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

public class KafkaProducerFactory {

    private static KafkaProducer kafkaProducer;

    public static KafkaProducer getKafkaProducer(String kafkaAddress, String kafkAsks, String kafkaRetry) {

        if(kafkaProducer == null){
            Properties properties = new Properties();
            properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaAddress);
            properties.put(ProducerConfig.ACKS_CONFIG, kafkAsks);
            properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
            properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
            if("true".equals(kafkaRetry)){
                properties.put(ProducerConfig.RETRIES_CONFIG, 5);
                properties.put(ProducerConfig.RETRY_BACKOFF_MS_CONFIG, 200);
                properties.put(ProducerConfig.DELIVERY_TIMEOUT_MS_CONFIG, 120000);
            }
            kafkaProducer = new KafkaProducer<>(properties);
        }

        return kafkaProducer;
    }
}
